import { useState, FC, useEffect } from 'react';
import FreeScrollBar from 'react-free-scrollbar'
import style from './index.module.less'
import { appName, companyName } from '@js/config'
import Menu from './menu'
import { AuthoritySchema } from '@src/components/schema/authority';
import { getMenuDataRequest } from './ajax'
import { useSelector } from 'react-redux';
import { INIT_BASIC_STATE } from '@redux/reducers/basic';
import { awaitWrap } from '@js/tool';
import { MenuSchema } from '@src/components/schema/menu';

const FreeScrollBarTag = FreeScrollBar as unknown as FC<any>

async function initData (id: string, setMenus: (v: MenuSchema[]) => void, setIsReady: (v: boolean) => void) {
  const [e, d] = await awaitWrap(getMenuDataRequest(id))
  if (e === null && d !== null) {
    setMenus(formatMenu(d))
    setIsReady(true)
  }
}
// 格式化菜单
function formatMenu (data: AuthoritySchema[]): MenuSchema[] {
  const list:MenuSchema[] = []
  data.forEach(o => {
    let children: MenuSchema[] = []
    if (o.children) {
      const l: MenuSchema[] = []
      const ks = o.children || []
      ks.forEach(c => {
        l.push({
          id: c.key,
          title: c.name,
          componentName: c.key,
          icon: c.ico,
          showChildren: true,
          children: []
        })
      })
      children = l
    }
    list.push({
      id: o.id,
      title: o.name,
      componentName: o.key,
      icon: o.ico,
      showChildren: true,
      children: children
    })
  })
  return list
}

export default function sider() {
  const [isReady, setIsReady] = useState(false)
  const [menus, setMenus] = useState<MenuSchema[]>([])
  const { userInfo } = useSelector((state: { basic: INIT_BASIC_STATE }) => {
   return {
    userInfo: state.basic.userInfo
   } 
  })
  useEffect(() => {
    initData(userInfo.id, setMenus, setIsReady)
  }, [])
  return (
    <div className={style.sider}>
      <div className={style.sider__header}>
        <span>{appName}</span>
      </div>
      <div className={style.sider__content}>
        {
          isReady && (
            <FreeScrollBarTag className='mock'>
              <ul className={style.menu}>
                <Menu data={menus} />
              </ul>
            </FreeScrollBarTag>
          )
        }
      </div>
    </div>
  )
}
